import React, { useState, useRef, useEffect, useImperativeHandle } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormGroup,
  ProFormList,
  ProFormDependency,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Tag, message, Upload, Drawer } from 'antd';
import {
  PlusOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

import type { ProFormInstance } from '@ant-design/pro-components';
import type { UploadProps } from 'antd';

import { useRequest } from 'umi';
import moment from 'moment';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const Task = (props: any) => {
  const editTaskRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState(false); //任务 抽屉

  useImperativeHandle(props.onRef, () => {
    return {
      showDrawer: showDrawer,
    };
  });

  const showDrawer = () => {
    setVisible(true);
  };

  const onClose = () => {
    setVisible(false);
  };

  //学生端——获取自己的任务列表
  const getMyTask = useRequest((data = null) => {
    return {
      url: `http://10.1.40.84:9998/stuTrain/getMyTask`,
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
    };
  });
  //学生端——获取任务详细
  const getMyOneTask = useRequest(
    (id = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getMyOneTask?id=${id}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );
  //学生端——更新任务
  const updateMyTask = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/updateMyTask`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: () => {
        props.refreshBadge();
        // getMyOverview.run();
      },
    },
  );

  const taskColumns = [
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
      // hideInSearch: true,
    },
    {
      title: '任务简介',
      dataIndex: 'taskDesc',
      key: 'taskDesc',
      // render: (text: any) => <Tag color={'blue'}>{text}</Tag>,
    },
    {
      title: '任务状态',
      dataIndex: 'recvState',
      key: 'recvState',
      render: (text: any) => {
        if (text === '0') {
          return (
            <Tag icon={<ClockCircleOutlined />} color="default">
              未读
            </Tag>
          );
        } else if (text === '1') {
          return (
            <Tag icon={<SyncOutlined spin />} color={'processing'}>
              进行中
            </Tag>
          );
        } else {
          return (
            <Tag icon={<CheckCircleOutlined />} color="success">
              已完成
            </Tag>
          );
        }
      },
    },
    {
      title: '导师',
      dataIndex: 'teaName',
      key: 'teaName',
    },
    {
      title: '任务开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    {
      title: '任务结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      align: 'center',
      render: (text: any, record: any) => [
        <ModalForm
          key="1"
          title={record?.taskName || '任务详情'}
          trigger={
            <a
              onClick={() => {
                getMyOneTask.run(record.id).then((e) => {
                  editTaskRef.current?.setFieldsValue(e);
                  getMyTask.run();
                  props.refreshBadge();
                });
              }}
            >
              查看任务
            </a>
          }
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
            destroyOnClose: true,
          }}
          submitTimeout={2000}
          onFinish={async (values) => {
            await waitTime(2000);
            updateMyTask.run({
              ...getMyOneTask?.data,
              materialList: values.materialList,
            });
            return true;
          }}
          submitter={{
            searchConfig: {
              submitText: '提交材料',
              resetText: '取消',
            },
            render: (props, defaultDoms) => {
              // console.log(props);
              if (record.recvState === '2') {
                return null;
              } else {
                return [...defaultDoms];
              }
            },
          }}
          formRef={editTaskRef}
          width={800}
        >
          <ProForm.Group>
            <ProFormText width="md" name="taskName" label="任务名称" disabled />
            <ProFormText width="md" name="taskDesc" label="任务简述" disabled />
            <ProFormDatePicker
              width="md"
              name="startTime"
              label="开始时间"
              disabled
            />
            <ProFormDatePicker
              width="md"
              name="endTime"
              label="结束时间"
              disabled
            />
          </ProForm.Group>
          <ProFormList
            name="materialList"
            label="材料信息"
            rules={[
              {
                validator: async (_, value) => {
                  // console.log(value);
                  if (value && value.length > 0) {
                    return;
                  }
                  throw new Error('至少要有一项！');
                },
              },
            ]}
            creatorButtonProps={{
              creatorButtonText: '添加材料',
              hidden: record.recvState === '2',
            }}
            copyIconProps={
              record.recvState === '2' ? false : { tooltipText: '复制' }
            }
            deleteIconProps={
              record.recvState === '2' ? false : { tooltipText: '删除' }
            }
          >
            {(meta: any, index: any, action: any, count: any) => {
              return (
                <ProFormGroup key="group">
                  <ProFormText
                    width="sm"
                    required
                    name="materialName"
                    label="材料名称"
                    disabled={record.recvState === '2'}
                  />
                  <ProFormSelect
                    label="材料类型"
                    name="materialType"
                    width="xs"
                    required
                    disabled={record.recvState === '2'}
                    valueEnum={{
                      学习报告: '学习报告',
                      参考文献: '参考文献',
                    }}
                  />
                  <ProFormDependency name={['materialType']}>
                    {({ materialType }) => {
                      if (materialType === '参考文献') {
                        return (
                          <ProFormText
                            width="sm"
                            name="materialContent"
                            label="文献链接"
                            required
                          />
                        );
                      } else if (
                        materialType === '学习报告' ||
                        materialType === '阶段性报告'
                      ) {
                        return (
                          <>
                            <Upload
                              {...props}
                              onChange={(info) => {
                                if (info.file.status === 'done') {
                                  action.setCurrentRowData({
                                    materialContent: info.file.response.data,
                                  });
                                  message.success(
                                    `${info.file.name} 上传成功！`,
                                  );
                                } else if (info.file.status === 'error') {
                                  message.error(
                                    `${info.file.name} file upload failed.`,
                                  );
                                }
                              }}
                            >
                              <Button
                                type="link"
                                style={
                                  index === 0
                                    ? { marginTop: 30 }
                                    : { marginTop: 0 }
                                }
                                disabled={record.recvState === '2'}
                              >
                                上传材料
                              </Button>
                            </Upload>

                            <ProFormText
                              width="sm"
                              name="materialContent"
                              required
                              hidden
                            />
                          </>
                        );
                      } else {
                        return null;
                      }
                    }}
                  </ProFormDependency>
                  <ProFormDependency name={['materialType']}>
                    {({ materialType }) => {
                      if (
                        materialType === '学习报告' &&
                        action.getCurrentRowData().materialContent
                      ) {
                        return (
                          <Button
                            type={'link'}
                            style={
                              index === 0 ? { marginTop: 30 } : { marginTop: 0 }
                            }
                            onClick={() => {
                              window.open(
                                action.getCurrentRowData().materialContent,
                              );
                            }}
                          >
                            下载
                          </Button>
                        );
                      } else {
                        return null;
                      }
                    }}
                  </ProFormDependency>
                </ProFormGroup>
              );
            }}
          </ProFormList>
        </ModalForm>,
        <Button
          key="2"
          type="link"
          size="small"
          disabled={record.recvState === '2'}
          onClick={() => {
            getMyOneTask.run(record.id).then((e) => {
              console.log(e);
              updateMyTask.run({ ...e, recvState: 2 }).then(() => {
                getMyTask.run();
                message.success('确认完成！');
              });
            });
          }}
        >
          确认完成
        </Button>,
      ],
    },
  ];

  return (
    <Drawer
      title="任务列表"
      placement="top"
      onClose={onClose}
      visible={visible}
      destroyOnClose
      height={450}
    >
      <ProTable
        columns={taskColumns}
        // cardBordered
        dataSource={getMyTask?.data || []}
        rowKey="id"
        search={false}
        pagination={{
          pageSize: 5,
          hideOnSinglePage: true,
        }}
        options={false}
        dateFormatter="string"
      />
    </Drawer>
  );
};

export default Task;
